import json

from backend.app.app.db.session_project import session_pro
import backend.app.app.models.db_owi_private_models as md_pro

"""
 下get_page_info 和 add_data 为接口read_page和save_page的方法
"""
def get_page_info(user_id:str,pro_id:str):
    try:
        project_inf = session_pro.query(md_pro.TbPageBP.user_id,
                                        md_pro.TbPageBP.proj_id,
                                        md_pro.TbPageBP.table_data,
                                        md_pro.TbPageBP.select_model,
                                        md_pro.TbPageBP.select_f_name,
                                        md_pro.TbPageBP.select_d_name,
                                        md_pro.TbPageBP.start_year)\
            .filter(md_pro.TbPageBP.user_id == user_id,
                    md_pro.TbPageBP.proj_id == pro_id).all()
        return project_inf
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        print('查找失败')
        session_pro.rollback()
        return False
#   新增数据
def add_data(page_data:dict):
    try:
        result = True
        # 判断是否已存在数据，有则改，无则增
        is_existed = session_pro.query(md_pro.TbPageBP).filter(
            md_pro.TbPageBP.proj_id == page_data.get("proj_id", None),
            md_pro.TbPageBP.user_id == page_data.get("user_id", None)).count()
        if is_existed:
            try:
                session_pro.query(md_pro.TbPageBP).filter(
                    md_pro.TbPageBP.proj_id == page_data.get("proj_id", None),
                    md_pro.TbPageBP.user_id == page_data.get("user_id", None)).update({
                    'table_data': page_data.get("table_data", None),
                    'select_model': page_data.get('select_model', None),
                    'select_f_name': page_data.get('select_f_name', None),
                    'select_d_name': page_data.get('select_d_name', None),
                    'start_year': page_data.get('start_year', None)
                })
                session_pro.commit()
            except Exception as e:
                return {'res': False, 'error': e}
        else:
            try:
                need_save_data = md_pro.TbPageBP(
                    user_id=page_data.get('user_id', None),
                    proj_id=page_data.get('proj_id', None),
                    table_data=page_data.get("table_data", None),
                    select_model=page_data.get('select_model', None),
                    select_f_name=page_data.get('select_f_name', None),
                    select_d_name=page_data.get('select_d_name', None),
                    start_year=page_data.get('start_year', None)
                )
                session_pro.add(need_save_data)
                session_pro.commit()
            except Exception as e:
                print(e)
                print(e.__traceback__.tb_lineno)
                return {'res': False, 'error': e}
        return {'res': True}
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        print(e.__traceback__.tb_frame.f_globals['__file__'])
        return {'res': False, 'error': e}


"""
 下get_page_data和 add_page_data 为接口read_page_data和save_page_data的方法
"""
def get_page_data(user_id:str,pro_id:str):
    try:
        project_inf = session_pro.query(md_pro.TbPageDataBP.user_id,
                                        md_pro.TbPageDataBP.proj_id,
                                        md_pro.TbPageDataBP.model_name,
                                        md_pro.TbPageDataBP.unit_name,
                                        md_pro.TbPageDataBP.start_end_date) \
            .filter(md_pro.TbPageDataBP.user_id == user_id,
                    md_pro.TbPageDataBP.proj_id == pro_id).all()
        return project_inf
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        print('查找失败')
        session_pro.rollback()
        return False

def add_page_data(page_data:dict):
    try:
        result = True
        # 判断是否已存在数据，有则改，无则增
        is_existed = session_pro.query(md_pro.TbPageDataBP).filter(
            md_pro.TbPageDataBP.proj_id == page_data.get("proj_id", None),
            md_pro.TbPageDataBP.user_id == page_data.get("user_id", None)).count()
        if is_existed:
            try:
                session_pro.query(md_pro.TbPageDataBP).filter(
                    md_pro.TbPageDataBP.proj_id == page_data.get("proj_id", None),
                    md_pro.TbPageDataBP.user_id == page_data.get("user_id", None)).update({
                    'model_name': page_data.get("model_name", None),
                    'unit_name': page_data.get('unit_name', None),
                    'start_end_date': page_data.get('start_end_date', None),
                })

                session_pro.commit()
            except Exception as e:
                print(e)
                print(e.__traceback__.tb_lineno)
                return {'res': False, 'error': e}

        else:
            try:
                need_save_data = md_pro.TbPageDataBP(
                    user_id=page_data.get('user_id', None),
                    proj_id=page_data.get('proj_id', None),
                    model_name=page_data.get("model_name", None),
                    unit_name=page_data.get('unit_name', None),
                    start_end_date=page_data.get('start_end_date', None),
                )
                session_pro.add(need_save_data)
                session_pro.commit()
            except Exception as e:
                print(e)
                print(e.__traceback__.tb_lineno)
                return {'res': False, 'error': e}

        return {'res': True}
    except Exception as e:
        print(e)
        print(e.__traceback__.tb_lineno)
        print(e.__traceback__.tb_frame.f_globals['__file__'])
        return {'res': False, 'error': e}



#   修改数据
def modify_data(data:dict):
    try:
        session_pro.query(md_pro.TbPageBP) \
            .filter(md_pro.TbPageBP.user_id == data["user_id"],
                    md_pro.TbPageBP.proj_id == data["proj_id"],
                    )\
            .update({
            md_pro.TbPageBP.table_data : data["table_data"],
            md_pro.TbPageBP.select_model: data["select_model"],
            md_pro.TbPageBP.select_f_name: data["select_f_name"],
            md_pro.TbPageBP.select_d_name: data["select_d_name"],
            md_pro.TbPageBP.start_year: data["start_year"]
        })
        session_pro.commit()
        print('更新数据成功')
        return True
    except:
        session_pro.rollback()
        print('更新数据失败')
        return False



#   删除数据
def delete_data(data:dict):
    try:
        session_pro.query(md_pro.TbPageBP) \
            .filter(md_pro.TbPageBP.user_id == data["user_id"],
                    md_pro.TbPageBP.proj_id == data["proj_id"]
                    ).delete()
        session_pro.commit()
        print('删除数据成功')
        return True
    except:
        session_pro.rollback()
        print('删除数据失败')
        return False